<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Config;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ConfigController extends CommonController
{
    //GET  admin/config  链接列表页面
    public function index()
    {
        $data = Config::orderBy('conf_order','desc')->get();

        foreach ($data as $k=>$v) {
            $str = ''; //radio 拼接出错，需要每次循环清空
            switch ($v->field_type) {
                case 'input' :
                    $str = '<input type="text" class="lg" size="70" name="conf_content[]" value="' . $v->conf_content . '">';
                    break;
                case 'textarea':
                    $str = '<textarea name="conf_content[]">' . $v->conf_content . '</textarea>';
                    break;
                case 'radio':
                    //1.先用,拆分  1|开启,0|关闭
                    $arr = explode(',', $v->field_value); // $arr = ['1|开启', '0|关闭']

                    foreach ($arr as $kk => $vv) {
                        $value = explode('|', $vv); //$value = ['1', '开启']

                        $flag = ($value[0] == $v->conf_content) ? 'checked' :''; // 判断单选框的选项

                        $str .= '<input type="radio" name="conf_content[]" value="'. $value[0] .'" '. $flag .'>' . $value[1] . '　';
                    }
                    break;
            }
            $data[$k]['_html'] = $str;
        }
        return view('admin.config.list')->with('data',$data);
    }

    //GET  admin/config/create 添加页
    public function create()
    {
        return view('admin.config.add');
    }

    //POST   admin/config  添加保存操作
    public function store($conf_id = 0)
    {
        //调用 insert/update 方法
        $rs = $this->auto_save($conf_id);
        if($rs === true) {
            return redirect('admin/config');
        }elseif($rs === false) {
            return back()->with('errors', '数据填充失败，请稍后重试！');
        }else {
            return back()->withErrors($rs);
        }
    }

    //GET   admin/config/{config}  展示单条记录页
    public function show($conf_id)
    {
        return redirect('admin/config');
    }

    //GET    admin/config/{config}/edit 编辑展示页
    public function edit($conf_id)
    {
        //获取编辑信息
        if( $info = Config::find($conf_id) ) {
            return view('admin.config.edit')->with(['info' => $info]);
        }
        return redirect('admin/config');
    }

    //PUT|PATCH   admin/config/{config}  更新操作
    public function update($conf_id)
    {
        //判断是否操作成功
        $rs = $this->auto_save($conf_id);
        if($rs === true) {
            //调用配置写入方法
            $rs = $this->database_to_file();
            return redirect('admin/config');
        }elseif($rs === false) {
            return back()->with('errors', '数据填充失败，请稍后重试！');
        }else {
            return back()->withErrors($rs);
        }
    }

    //DELETE   admin/config/{config}  删除记录操作
    public function destroy($conf_id)
    {
        if( $rs = Config::where('conf_id', $conf_id)->delete() ) {
            //调用配置写入方法
            $rs = $this->database_to_file();
            $data = ['msg' => '删除成功', 'errno' => 0];
        }else {
            $data = ['msg' => '删除失败', 'errno' => 2];
        }
        return $data;
    }

    /**
     * 验证插入、保存数据的方法,返回三种结果 true,false,Validator类
     * @param int $conf_id 主键id
     * @return bool | object
     */
    public function auto_save($conf_id = 0)
    {
        //3月1日 新增一条验证规则
        if(!is_numeric($conf_id)) return false;

        if( $input = Input::except('_token','_method') ) {
            $rule = [
                'conf_title'=> 'required',
                'conf_name' => 'required',
                'field_type'  => 'required',
            ];
            $message = [
                'conf_title.required'   =>  '中文名称不能为空',
                'conf_name.required'    =>  '英文名称不能为空',
                'field_type.required'    =>  '类型不能为空'
            ];

            $validator = Validator::make($input, $rule, $message);

            if($validator->passes()) {
                //验证通过，插入/更新 数据库
                if($conf_id) { //更新操作
                    $rs = Config::where('conf_id', $conf_id)->update($input);
                }else { //插入操作
                    $rs = Config::create($input);
                }
                //判断是否操作成功
                if($rs !== false) {
                    return true;
                }else {
                    return false;
                }
            }else {
                //验证失败时，更新操作需要单独处理
                return $validator;
            }
        }
    }

    //配置列表，表单提交保存配置信息
    public function save_config()
    {
        $input = Input::all();
        $flag = 1;
        foreach ($input['conf_id'] as $k=>$v) {
            //遍历插入数据
            $rs = Config::where('conf_id', $v)->update([ 'conf_content' => $input['conf_content'][$k] ]);
            if($rs === false) $flag = 0;
        }

        //调用配置写入方法
        $rs = $this->database_to_file();
        if(!$flag || !$rs) {
            return back()->with('errors','配置设置失败，请稍后重试!');
        }
        return back()->with('errors','配置设置成功!');
    }

    //配置信息写入 文件
    public function database_to_file()
    {
        //方法一：比较麻烦
        /*$config = Config::get(['conf_name', 'conf_content']);
        $data = '<?php return [ '; // 'web_name' => 'blog',
        foreach ($config as $v) {
            $data .=  "'" . $v->conf_name ."'" . ' => ' . "'" . $v->conf_content . "'" . ',';
        }
        $data .= ']; ?>';
        */
        //方法二：
        $config = Config::pluck('conf_content','conf_name')->all(); //直接生成二维数组

        /*$list = Config::get(['conf_name', 'conf_content']);
        $config = [];
        foreach ($list as $v) {
            $config[$v->conf_name] = $v->conf_content;
        }*/

        $data = '<?php return ';
        $data .= var_export($config, true);
        $data .= '; ?>';

        $rs = file_put_contents(base_path() . '/config/web.php', $data);
        if($rs !== false) {
            return true;
        }else {
            return false;
        }
    }
}

